package selecthx;
import js.Dom;
import js.Lib;

class DomUtils {
	public static function getById(id:String, ?tag:String, ?context:HtmlDom):Null<HtmlDom> {
		if (context == null)
			context = Lib.document;
		var candidate = Lib.document.getElementById(id);
		if (candidate == null)
			return null;		
		if (context != Lib.document) {
			/* You can only use getElementById on a document.
			 * We can still use it to find an element if we are using a context,
			 * we just have to walk up the tree to see if it is under it */
			var next = candidate;
			while (true) {
				if (next == null)
					return null;				
				if (next == context)
					break;					
				next = next.parentNode;
			}
		}
		if (tag != null && candidate.nodeName != tag.toUpperCase())
			return null;
		return candidate;
	}
		
	public static function getByClasses(classes:Array<String>, ?tag:String, ?context:HtmlDom):Array<HtmlDom> {
		if (context == null)
			context = Lib.document;
		if (untyped context.getElementsByClassName != null) {
			var list:HtmlCollection<HtmlDom> = 
				untyped context.getElementsByClassName(classes.join(" "));			
			var result = [];
			for (i in 0 ... list.length)
				result.push(list[i]);
			return result;
		}
		if (tag == null)
			tag = "*";
		var list = context.getElementsByTagName(tag);
		var result = [];
		for (i in 0 ... list.length) {
			var el = list[i];
			var names = el.className.split(" ");
			for (i in classes) {
				for (j in names) {
					if (i == j) {
						result.push(el);
						break;
					}
				}
			}			
		}
		return result;
	}
}